package com.crm.smartmachine.base

import android.os.Bundle
import androidx.annotation.IdRes
import androidx.annotation.Nullable
import androidx.databinding.ViewDataBinding
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.cheng.library.base.BaseFragment
import com.cheng.library.common.toast
import com.crm.smartmachine.R
import com.crm.smartmachine.contants.EventConstants
import com.crm.smartmachine.event.Message
import com.crm.smartmachine.network.ResponseThrowable
import com.crm.smartmachine.viewmodel.MainViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

abstract class SmartBaseFragment<BD : ViewDataBinding> : BaseFragment<BD>() {

    protected val viewModel: MainViewModel by viewModel()

    protected val currentFragment by lazy {
        activity?.supportFragmentManager?.findFragmentById(R.id.fragment_main)?.childFragmentManager?.primaryNavigationFragment
    }

    override fun init(savedInstanceState: Bundle?) {

    }

    override fun onResume() {
        super.onResume()
        viewModel.defUI.msgEvent.postValue(
            Message(
                0,
                EventConstants.START_COUNT_DOWN,
                obj = currentFragment
            )
        )
    }

//    override fun onPause() {
//        super.onPause()
//        LogUtils.a("onPause：" + currentFragment)
//    }

    fun handleErrorResponse(response: ResponseThrowable) {
        toast("${response.code};${response.errMsg}")
    }

    fun navigateDelay(@IdRes resId: Int) {
        postDelayed({
            navigate(resId)
        }, 300L)
    }

    fun navigate(@IdRes resId: Int) {
        navigate(resId, null)
    }

    fun navigate(@IdRes resId: Int, @Nullable args: Bundle?) {
        nav().navigate(resId, args)
    }

    fun navigateBack() {
        nav().navigateUp()
    }

    fun hideSoftInput() {
        activity?.let {
            KeyboardUtils.hideSoftInput(it)
        }
    }
}